﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace TestNewLandCloud
{
    /// <summary>
    /// Http请求方法
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// 服务端IP
        /// </summary>
        public string ServerIP
        {
            get;
            set;
        }
        /// <summary>
        /// 返回结果
        /// </summary>
        public string ResultMsg { get; set; }
        /// <summary>
        /// Http标头
        /// </summary>
        private string _Accept { get; set; }
        /// <summary>
        /// 请求方法
        /// </summary>
        private string _Method { get; set; }
        /// <summary>
        /// 标头值
        /// </summary>
        private string _ContentType { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accept"></param>
        /// <param name="method"></param>
        /// <param name="contentType"></param>
        public HttpHelper(string serverIP = "", string accept = "application/text", string method = "POST", string contentType = "application/json")
        {
            ServerIP = serverIP;
            _Accept = accept;
            _Method = method;
            _ContentType = contentType;
        }
        /// <summary>
        /// 请求消息
        /// </summary>
        /// <param name="model">提交的数据</param>
        /// <param name="controller">控制器</param>
        /// <param name="method">方法名</param>
        /// <param name="headName">token名称</param>
        /// <param name="accessToken">token值</param>
        public void RequestData(object model, string controller, string method, string headName = "AccessToken", string accessToken = "")
        {
            if (model != null)
            {
                string url = string.Format("api/{0}/{1}", controller, method);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServerIP + url);
                request.Accept = _Accept;
                request.Method = _Method;
                request.Headers.Add(headName, accessToken);
                request.ContentType = _ContentType;
               // Dictionary<string, object> dic = new Dictionary<string, object>();
                string data = JsonConvert.SerializeObject(model);
                byte[] buffer = Encoding.UTF8.GetBytes(data);

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(buffer, 0, buffer.Length);
                requestStream.Close();
                request.BeginGetResponse(new AsyncCallback(ProcessData), request);

           

            }
        }

        /// <summary>
        /// 请求消息
        /// </summary>
        /// <param name="model">提交的数据，或是方法名称</param>
        /// <param name="dataEncode">编码格式</param>
        public void RequestData(object model, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                string paramData = JsonConvert.SerializeObject(model);
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(ServerIP));
                webReq.Method = _Method;
                webReq.ContentType = _ContentType;

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ResultMsg = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
               // RecordLog.Write(ex.Message);
            }

        }


        /// <summary>
        /// 异步获取数据
        /// </summary>
        /// <param name="ar"></param>
        private void ProcessData(IAsyncResult ar)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
                using (var sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                {
                    ResultMsg = sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
               // RecordLog.Write(ex.Message);
            }
        }
    }
}
